<template>
  <div class="permission-management-container">
    <!-- 顶部标题和角色切换 -->
    <div class="header-section">
      <div class="title-container">
        <h1 class="system-title" style="color: #3998a9;">权限管理</h1>
      </div>
      <div class="role-switcher">
        <span class="role-label">当前角色：</span>
        <el-select v-model="currentRole" @change="handleRoleChange" class="role-select" size="large">
          <el-option label="超级管理员" value="superAdmin" />
          <el-option label="普通管理员" value="admin" />
          <el-option label="普通用户" value="user" />
        </el-select>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content-card">
      <!-- 操作按钮区 -->
      <div class="action-bar">
        <div class="left-actions">
          <el-button type="primary" @click="showAddDialog" v-if="hasPermission('permission:create')"
            class="action-button">
            <el-icon>
              <Plus />
            </el-icon>
            新增权限
          </el-button>
        </div>
      </div>

      <!-- 权限表格 -->
      <el-table :data="permissionStore.permissions" border style="width: 100%" v-loading="permissionStore.loading"
        class="permission-table" :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
        <el-table-column prop="permissionName" label="权限名称" width="180" align="center" />
        <el-table-column prop="code" label="权限代码" align="center" />
        <el-table-column prop="isActive" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'danger'" effect="dark">
              {{ row.isActive ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" align="center" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button size="small" type="primary" plain @click="editPermission(row)"
                v-if="hasPermission('permission:edit')" class="operation-button">
                <el-icon>
                  <Edit />
                </el-icon>
                编辑
              </el-button>
              <el-button size="small" :type="row.isActive ? 'warning' : 'success'" plain
                @click="togglePermissionStatus(row)"
                v-if="hasPermission('permission:toggle') && currentRole !== 'admin'" class="operation-button">
                <el-icon>
                  <Switch />
                </el-icon>
                {{ row.isActive ? '禁用' : '启用' }}
              </el-button>
              <el-button size="small" type="danger" plain @click="handleDelete(row.id)"
                v-if="hasPermission('permission:delete')" class="operation-button"
                :loading="permissionStore.loading && permissionStore.currentPermission?.id === row.id">
                <el-icon>
                  <Delete />
                </el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="permissionStore.page" v-model:page-size="permissionStore.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          :total="permissionStore.total" @size-change="handleSizeChange" @current-change="handlePageChange"
          background />
      </div>
    </div>

    <!-- 添加/编辑权限对话框 -->
    <el-dialog v-model="permissionStore.dialogVisible" :title="permissionStore.isEdit ? '编辑权限' : '新增权限'" width="500px"
      :close-on-click-modal="false" @closed="permissionStore.closeDialog()">
      <!-- 新增：防御式渲染 -->
      <el-form v-if="permissionStore.currentPermission" :model="permissionStore.currentPermission" label-width="100px"
        :rules="formRules" ref="permissionFormRef" label-position="right">
        <el-form-item label="权限名称：" prop="permissionName">
          <el-input v-model="permissionStore.currentPermission.permissionName" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item label="权限代码：" prop="code">
          <el-input v-model="permissionStore.currentPermission.code" placeholder="请输入权限代码（如：role.edit）" clearable />
        </el-form-item>
        <!-- <el-form-item label="状态：" v-if="permissionStore.isEdit && currentRole !== 'admin'">
          <el-switch v-model="permissionStore.currentPermission.isActive" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="创建时间：" v-if="permissionStore.isEdit">
          <el-text>{{ permissionStore.currentPermission.createTime || '--' }}</el-text>
        </el-form-item>
        <el-form-item label="更新时间：" v-if="permissionStore.isEdit">
          <el-text>{{ permissionStore.currentPermission.updateTime || '--' }}</el-text>
        </el-form-item> -->
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionStore.closeDialog()">取消</el-button>
          <el-button type="primary" @click="submitPermissionForm" :loading="permissionStore.loading">
            {{ permissionStore.isEdit ? '保存更改' : '确认新增' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<!-- 以下 script 和 style 与你原文件完全一致，无需改动 -->
<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Edit, Switch } from '@element-plus/icons-vue'
import { usePermissionStore } from '@/stores/permissionStore'

const permissionStore = usePermissionStore()

// 角色权限配置
const rolePermissions = {
  superAdmin: ['*:*:*'], // 所有权限
  admin: [
    'permission:view',
    'permission:create',
    'permission:edit',
    'permission:delete',
    'permission:toggle'
  ],
  user: ['permission:view']
}

// 当前角色
const currentRole = ref('superAdmin')
const permissionFormRef = ref(null)

// 表单验证规则
const formRules = {
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限代码', trigger: 'blur' },
    {
      pattern: /^[a-z][a-zA-Z.]{2,49}$/,
      message: '必须以小写字母开头，可包含字母和点号，3-50个字符',
      trigger: 'blur'
    }
  ]
}

// 检查权限
const hasPermission = (permission) => {
  if (currentRole.value === 'superAdmin') return true
  const permissions = rolePermissions[currentRole.value] || []
  return permissions.includes('*:*:*') || permissions.includes(permission)
}

// 角色变更处理
const handleRoleChange = (role) => {
  const roleName =
    role === 'superAdmin' ? '超级管理员' : role === 'admin' ? '普通管理员' : '普通用户'
  ElMessage.success(`已切换为${roleName}角色`)
  permissionStore.fetchPermissions()
}

// 显示添加对话框
const showAddDialog = () => {
  permissionStore.openEditDialog(null)
}

// 编辑权限
const editPermission = (row) => {
  permissionStore.openEditDialog(row)
}

// 分页大小变化
const handleSizeChange = (size) => {
  permissionStore.setPageSize(size)
}

// 页码变化
const handlePageChange = (page) => {
  permissionStore.setPage(page)
}

// 删除权限
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该权限吗？此操作不可撤销！',
      '删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'error',
        distinguishCancelAndClose: true
      }
    )
    await permissionStore.deletePermission(id)
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
    }
  }
}

// 切换权限状态
const togglePermissionStatus = async (permission) => {
  await permissionStore.togglePermissionStatus(permission)
}

// 提交权限表单
const submitPermissionForm = async () => {
  try {
    if (!permissionStore.currentPermission || !permissionFormRef.value) {
      ElMessage.warning('表单数据未正确初始化')
      return
    }
    await permissionFormRef.value.validate()
    if (
      !permissionStore.currentPermission.permissionName ||
      !permissionStore.currentPermission.code
    ) {
      ElMessage.warning('请填写完整的权限信息')
      return
    }
    const success = permissionStore.isEdit
      ? await permissionStore.editPermission(
        permissionStore.currentPermission.id,
        permissionStore.currentPermission
      )
      : await permissionStore.addPermission(permissionStore.currentPermission)
    if (success) permissionStore.closeDialog()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('表单提交失败:', error)
      ElMessage.error('表单提交失败: ' + (error.message || '未知错误'))
    }
  }
}

// 初始化
onMounted(() => {
  permissionStore.fetchPermissions()
})
</script>
<style scoped>
.permission-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.title-container {
  display: flex;
  align-items: center;
  gap: 16px;
}

.system-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.module-title {
  font-size: 18px;
  font-weight: 500;
  color: #606266;
  margin: 0;
}

.divider {
  width: 2px;
  height: 24px;
  background-color: #dcdfe6;
}

.role-switcher {
  display: flex;
  align-items: center;
  gap: 10px;
}

.role-label {
  font-size: 14px;
  color: #606266;
}

.role-select {
  width: 150px;
}

.main-content-card {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.action-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.left-actions {
  display: flex;
  gap: 12px;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 6px;
}

.permission-table {
  margin-top: 15px;
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
}

.operation-button {
  display: flex;
  align-items: center;
  gap: 6px;
  margin: 2px 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>